package com.ruoyi.framework.config;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.ruoyi.framework.config.properties.SSHConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;

//@Configuration
//@ConditionalOnProperty(name = "ssh.enabled", havingValue = "true", matchIfMissing = false)
public class DataSourceConfig {
    @Autowired
    private SSHConfig sshConfig;

    @Value("${spring.datasource.druid.master.url}")
    private String databaseUrl;

    @Value("${spring.datasource.druid.master.username}")
    private String databaseUsername;

    @Value("${spring.datasource.druid.master.password}")
    private String databasePassword;

    @Bean
    @Primary
    public DataSource dataSource() throws SQLException {
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(sshConfig.getUsername(), sshConfig.getHost(), sshConfig.getPort());
            session.setPassword(sshConfig.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            int localPort = session.setPortForwardingL(0, "localhost", 3306);
            return new DriverManagerDataSource("jdbc:mysql://localhost:" + localPort + "/xzs?useSSL=false", databaseUsername, databasePassword);
//            return new DriverManagerDataSource(databaseUrl);

        } catch (Exception e) {
            throw new SQLException("Error setting up SSH tunnel and database connection", e);
        }
    }
}
